package main

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	//"os"
	"time"
)

type Hash struct {
	Hash string `xorm:pk varchar(25) not null unique`
	//Magnet     string
	Title      string
	File       string
	Filenumber int
	Time       int64
	Filesize   int64
	Indextime  int64
}

// 保存结果到数据库
func writeToDb() {
	engine, err := xorm.NewEngine("mysql", "codeit:kofj@/codeit?charset=utf8")
	defer engine.Close()
	// 调试信息
	//engine.ShowSQL = true
	//engine.ShowDebug = true
	//engine.ShowError = true
	//engine.ShowWarn = true
	// 自动同步表结构
	err = engine.Sync(new(Hash))
	if err != nil {
		fmt.Println(err)
	}

	/*
		if os.Args[5] != "" {
			// 日志
			f, err := os.Create(os.Args[5] + ".log")
			if err != nil {
				println(err.Error())
				return
			}
			engine.Logger = xorm.NewSimpleLogger(f)
		}
	*/
	s, ok := <-result
	for ok {
		time.Sleep(50 * time.Millisecond)
		//fmt.Println(write, s.hash)
		insertData := &Hash{
			Hash: s.hash,
			//Magnet:     s.magnet,
			Title:      s.title,
			File:       s.file,
			Filenumber: s.fileNumber,
			Time:       s.time,
			Filesize:   s.fileSize,
			Indextime:  s.indexTime,
		}
		_, err = engine.Insert(insertData)
		if err != nil {
			fmt.Println(err)
			//return
		}

		fmt.Println("写入数据库成功", s.hash)
		s, ok = <-result
	}
	// 等待结果保存完成后通知进程退出
	clo <- true
}
